<template>
  <div>
    <div class="form">
      <!-- 表单输入元件 ----------------------------------------------------------------------------------------->
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" class="rule-form">
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="ruleForm.materialName" placeholder="请输入物料名称" />
        </el-form-item>

        <el-form-item label="类别" prop="typeId">
          <el-select v-model="ruleForm.typeId" value-key="typeId" filterable placeholder="请选择类别">
            <el-option v-for="item in capabilityTypeOptions" :key="item.typeId" :label="item.typeName" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="规格型号" prop="model">
          <el-input v-model="ruleForm.model" placeholder="请输入规格型号" />
        </el-form-item>

        <el-form-item label="单位" prop="unit">
          <el-select v-model="ruleForm.unit" filterable placeholder="请选择单位">
            <el-option v-for="item in DictionaryList" value-key="dictValue" :key="item.dictValue"
              :label="item.dictLabel" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="类型" prop="kind">
          <el-select v-model="ruleForm.kind" placeholder="请选择配件名称" @change="handleSelect">
            <el-option v-for="(v, k) in ['耗材', '配件']" :key="k" :label="v" :value="k" />
          </el-select>
        </el-form-item>

        <el-form-item label="库存预警" prop="lowerLimit">
          <div class="inventory">
            <el-input-number v-model="ruleForm.lowerLimit" :min="0" label="请输入库存预警下限" controls-position="right" />
            <div style="margin:0 10px">
              ~
            </div>
            <el-input-number v-model="ruleForm.highLimit" :min="ruleForm.lowerLimit + 1" label="请输入库存预警上限"
              controls-position="right" />
          </div>
        </el-form-item>

        <el-form-item label="采购周期（天）" prop="purchaseCycle">
          <el-input-number v-model="ruleForm.purchaseCycle" :min="ruleForm.purchaseCycle || 0"
            controls-position="right" />
        </el-form-item>

        <el-form-item label="更换周期（天）" prop="replaceCycle">
          <el-input-number v-model="ruleForm.replaceCycle" :min="ruleForm.replaceCycle || 0"
            controls-position="right" />
        </el-form-item>

        <el-form-item label="备注">
          <el-input type="textarea" placeholder="请输入备注" v-model="ruleForm.remark" maxlength="50" show-word-limit>
          </el-input>
        </el-form-item>

        <el-form-item label="图片" prop="image">
          <upload-image :imgUrl="ruleForm.image" @clearimgUrl="() => ruleForm.image = ''"
            @handleSuccess="handleSuccess">
          </upload-image>
        </el-form-item>

        <el-form-item label="附件" prop="file">
          <FileUpload v-model="ruleForm.file" :limit="1" :fileSize="50"
            :fileType="['xls', 'xlsx', 'doc', 'docx', 'pdf', 'jpg', 'png']">
          </FileUpload>
        </el-form-item>

        <el-form-item v-if="ruleForm.kind" label="适用设备" prop="consumableEquipments">
          <el-select v-model="ruleForm.consumableEquipments" filterable multiple placeholder="请输入关键词">
            <el-option v-for="(item, i) in applicableList" :key="i"
              :label="item.equipmentName + '(' + item.equipmentNum + ')'" :value="item.equipmentAccountId" />
          </el-select>
        </el-form-item>
      </el-form>
      <!-- ----------------------------------------------------------------------------------------------------->
    </div>
    <div class="dialog_footer">
      <el-button type="primary" @click="handleConfirm">提交</el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
  </div>
</template>

<script>
/** 远程添加，修改，获取单个详性接口，获取selector下拉列表的接口，以及时间转换工具函数等 ------------------------------------------------- */
import { listSort, listDictionary, listSupplier, listApplicable, add, update, listDetail, checkUniqeByName } from '@/api/deviceConsumable/management'
import UploadImage from '@/components/upload/index.vue'
/** ------------------------------------------------------------------------------------------------------------------------------- */

/** 表单参数 ------------------------------------------------------------------------------------------------------------------------ */
const ruleForm = {
  materialName: null, //物料名称
  typeId: null, //类别ID
  model: null, //规格型号
  unit: null, //单位
  kind: 0, //类型（0耗材 1备件）
  lowerLimit: 0, //库存预警下限
  highLimit: 0, //库存预警上限
  purchaseCycle: 0, //采购周期（天）
  replaceCycle: 0, //更换周期（天）
  consumableEquipments: [], //设备集合
  image: '', //备件耗材图片
  file: '', //备件耗材附件
  remark: '' //备注
}
/** ---------------------------------------------------------------------------------------------------------------------------------- */

export default {
  name: 'Form',
  components: {
    UploadImage
  },
  data () {
    return {
      dialogVisible: false,
      ruleForm: Object.assign({}, ruleForm),
      isUpdateForm: false,
      dialogTitle: '添加基值',
      capabilityTypeOptions: [],
      DictionaryList: [],
      SupplierList: [],
      applicableList: [],
      fileList: [], // 上传附件的本地数组
      /** 表单规则 --------------------------------------------------------------------------------------------------------------------- */
      rules: {
        materialName: [
          { required: true, message: '请输入物料名称', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        typeId: [
          { required: true, message: '请选择类别', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        unit: [
          { required: true, message: '请选择单位', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        kind: [
          { required: true, message: '请选择配件', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        image: [
          { required: true, message: '请上传图片', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        consumableEquipments: [
          { required: true, message: '请选择适用设备（可多选）', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
      }
      /** ----------------------------------------------------------------------------------------------------------------------------- */
    }
  },
  created () {
    this.handleListType()
  },
  methods: {
    // 类型和字典单位数据接口---------------------------------------------
    async handleListType () {
      const { data: res } = await listSort({ status: 0 }) //类型
      const { data: dictionary } = await listDictionary({ dictType: 'base_unit', status: 0 })//字典单位
      const { data: supplier } = await listSupplier({ status: 0 })// 供应商
      this.capabilityTypeOptions = res
      this.DictionaryList = dictionary
      this.SupplierList = supplier
    },

    // 选择配件时调用适用设备列表-------------------------------------
    handleSelect (val) {
      listApplicable({ 'params[userStatuses]': '0,1,2,4' }).then(res => {
        this.applicableList = res.data
      })
    },
    // 图片上传时的处理方法-------------------------------------------
    handleSuccess (res) {
      this.ruleForm.image = res.res.data.url
    },
    // 打开表单对话框
    openDialog (id = null) {
      if (id) {
        listDetail(id).then(res => {
          this.isUpdateForm = true
          this.dialogTitle = '修改基值'
          /** 修改时的表单参数赋值 --------------------------------------------------------------------------------------------------------------------- */
          this.ruleForm = res.data
          this.ruleForm.kind = res.data.kind * 1
          this.ruleForm.consumableEquipments = res.data.eaPartInfoVos ? res.data.eaPartInfoVos.map(item => item.equipmentAccountId) : []
          this.dialogVisible = true
          console.log(this.ruleForm.consumableEquipments);
        })
      } else {
        this.isUpdateForm = false
        this.dialogTitle = '添加基值'
        this.dialogVisible = true
      }
      this.handleListType()
      this.handleSelect()
    },
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = Object.assign({}, this.ruleForm)
          data.consumableEquipments = this.ruleForm.consumableEquipments.map(item => {
            return {
              equipmentAccountId: item
            }
          })
          console.log('提交的表单', data)
          if (this.isUpdateForm) {
            update(data).then((res) => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.resetForm('ruleForm')
              this.dialogVisible = false
              this.$emit('submit_success')
            })
          } else {
            data.typeId = this.ruleForm.typeId.typeId
            data.typeName = this.ruleForm.typeId.typeName
            data.unit = this.ruleForm.unit.dictValue
            data.unitName = this.ruleForm.unit.dictLabel
            checkUniqeByName({ materialName: this.ruleForm.materialName }).then((res) => {
              if (res.data == 0) {
                this.$emit('parent_indexA', data)
              } else {
                this.$message({
                  message: '已存在相同物料，请重新输入！',
                  type: 'error'
                })
              }
            })
            // add(data).then((res) => {
            //   this.$message({
            //     message: '创建成功',
            //     type: 'success'
            //   })
            //   this.fileList = []
            //   this.ruleForm.consumableEquipments = []
            //   this.$nextTick(function () {
            //     this.$refs['ruleForm'].clearValidate()
            //   });
            //   this.resetForm('ruleForm')
            //   this.dialogVisible = false
            //   this.$emit('submit_success')
            // })
          }
        } else {
          this.$message({
            message: '数据验证不通过，检查输入表单',
            type: 'error'
          })
          return false
        }
      })
    },
    // 重置表单
    resetForm (formName) {
      if (this.isUpdateForm) {
        this.$refs[formName].resetFields()
      } else {
        this.ruleForm = Object.assign({}, ruleForm)
        this.ruleForm.consumableEquipments = []
        this.fileList = []
      }
      // --------consolelog('重置表单', this.ruleForm)
    },
    /** ---------------------------------------------------------------------------------------------------------------------------------------- */
    // 关闭窗口，重置表单
    handleClose () {
      this.$emit('parent_close')
      // this.ruleForm = Object.assign({}, ruleForm)
      // this.dialogVisible = false
      // this.fileList = []
      // this.ruleForm.consumableEquipments = []
      // this.$nextTick(function () {
      //   this.$refs['ruleForm'].clearValidate()
      // });
    },
    handleConfirm () {
      this.submitForm('ruleForm')
    },
    handleReset () {
      this.resetForm('ruleForm')
    }
  }
}
</script>
<style lang="scss" scoped>
.form {
  margin-left: auto;
  margin-right: auto;

  .inventory {
    display: flex;
  }
}

::v-deep .el-select {
  width: 100%;
}

::v-deep .el-input-number {
  width: 100%;
}

.dialog_footer {
  display: flex;
  justify-content: center;
}
</style>
